<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ivan
 * Date: 8/17/12
 * Time: 3:59 PM
 * To change this template use File | Settings | File Templates.
 */
 
class Menus extends Engine {

    public static function showMenu($identifier, $template = '') {

        if (!empty($identifier)) {
            $items = Db_Cms_Menus::getItems($identifier);


			if(strlen($template) == 0) {
				if(isset($items[0]['m_template'])) {
					$template = $items[0]['m_template'];
				} else {
					$template = 'template_no_exists';
				}
			}

			$menuTree = self::createTreeMenus($items);

            self::$TPL->assign('menuTree', $menuTree);
            self::$TPL->display($template);

            return;
        } else {
            trigger_error('Menu::showMenu(?) - Identifier is missing', E_USER_ERROR);
        }

    }   
	
	public static function createTreeMenus($allMenus = array(), $parent=0) {
		if (is_array($allMenus) && count($allMenus) > 0) {
			$refs = array();
			$list = array();
			//krsort($allMenus);
			foreach($allMenus as $data) {
				$thisRef = &$refs[ $data['id'] ];

				$thisRef['parent_id'] = $data['mp_parent_id'];
				$thisRef['url'] = $data['p_url'];
				$thisRef['title'] = $data['mp_item_title'];
				$thisRef['icon'] = $data['mp_item_icon'];
                $thisRef['display'] = isset($data['mp_display']) ? $data['mp_display'] : false;
				$thisRef['id'] = $data['id'];
                $thisRef['menu_id'] = $data['mp_menu_id'];
                $thisRef['position'] = $data['mp_position'];
                $thisRef['menu_page_id'] = $data['menu_page_id'];
                $thisRef['pm_identifier'] = isset($data['pm_identifier']) ? $data['pm_identifier'] : false;

				if ($data['mp_parent_id'] == $parent) {
					$list[ $data['id'] ] = &$thisRef;
				} else {
					$refs[$data['mp_parent_id']]['childs'][$data['id']] = &$thisRef;
				}
			}
			return $list;
		}
		return array();
	}

	/**
	 * @static
	 * @param $menuTree
	 * @param array $configArray
	 * @param bool $isRoot
	 * @return array|string
	 */
	public static function createHtmlMenu(
		$menuTree,
		$configArray = array(
			'menuOpen' => '<ul id="nav">',
			'menuClose' => '</ul>',
			'listOpen' => '<ul [#listAttr#] [#listParams#]>',
			'listClose' => '</ul>',
			'openedListParams' => 'style="display:block"',
			'closedListParams' => '',
			'listAttr' => '',
			'itemOpen' => '<li [#itemAttr#] [#itemClass#] [#itemId#]>',
			'itemClose' => '</li>',
			'link' => '<a href="[#url#]" [#linkAttr#] [#linkClass#]><span>[#text#]</span></a>',
			'itemAttr' => '',
			'itemActiveClass' => '',
			'itemIdPrefix' => 'left_menu_',
			'itemLevelClassPrefix' => 'left_menu_',
			'linkAttr' => '',
			'linkActiveClass' => 'active'
		),
		$isRoot = true)
	{

		$current = get('page', 'string');

		$liHtml = '';
		$classOpened = false;
		$isActive = false;
		foreach ($menuTree as $value) {

			if ($value['pm_identifier']) {
				if(!perm($value['pm_identifier'])) {
					continue;
				}
			}
			if (empty($value['title'])) continue;

			$tempChildsHtml = '';
			$classActive = '';

			if ($current ===  $value['url']) {
				$isActive = true;
				$classActive = $configArray['linkActiveClass'];
			}

			if (isset($value['childs'])) {
				$result = self::createHtmlMenu($value['childs'], $configArray, false);
				if (!$result[2]) {
					continue;
				}
				$tempChildsHtml = $result[0];
				if ($result[1]) {
					$classOpened = true;
					$isActive = true;
					$classActive = $configArray['linkActiveClass'];
				}
			}


			$liClass = (isset($value['icon'])) ? $value['icon'] : '';

			$liItemHtml = str_replace('[#itemAttr#]', $configArray['linkAttr'], $configArray['itemOpen']);
			$liItemHtml = str_replace('[#itemClass#]', 'class="'.$configArray['itemActiveClass'] . ' '. $configArray['itemLevelClassPrefix'] . $value['id'] . ' ' . $liClass .'"', $liItemHtml);
			$liItemHtml = str_replace('[#itemId#]', 'id="'.$configArray['itemIdPrefix'] . $value['id'] .'"', $liItemHtml);

			if (isset($value['childs'])) {
				$urlReplace = '#';
				$linkAttr = 'onclick="return false"';
			} else {
				$urlReplace = '/' . $value['url'];
				$linkAttr = '';
			}


			$linkHtml = str_replace('[#url#]', $urlReplace, $configArray['link']);

			$linkHtml = str_replace('[#linkAttr#]', $configArray['linkAttr'] . $linkAttr , $linkHtml);
			$linkHtml = str_replace('[#linkClass#]', 'class="'.$classActive.'"', $linkHtml);
			$linkHtml = str_replace('[#text#]', t(T_MENU_LABEL, $value['title']), $linkHtml);
			$liItemHtml .= $linkHtml . $tempChildsHtml . $configArray['itemClose'];
			$liHtml .= $liItemHtml;
		}

		if ($isRoot) {
			$ulHtml = $configArray['menuOpen'];
		} else {
			$displayBlock = ($classOpened || $isActive) ? $configArray['openedListParams'] : $configArray['closedListParams'];
			$ulHtml = str_replace('[#listAttr#]',$configArray['listAttr'],$configArray['listOpen']);
			$ulHtml = str_replace('[#listParams#]',$displayBlock, $ulHtml);
		}

		$resultHtml = $ulHtml.$liHtml.$configArray['listClose'];
		if (!$isRoot) {
			return array($resultHtml, $isActive,(!empty($liHtml) ? true : false));
		}
		return $resultHtml;

	}
}
